package com.util.Ali;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.stereotype.Component;

@Component
public class SendSms {
    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config();
        // 您的AccessKey ID
        config.setAccessKeyId(accessKeyId);
        // 您的AccessKey Secret
        config.setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 短信发送
     *
     * @param code: 验证码
     * @return {@link Boolean}
     */
    public static boolean sendSms(String phone, String code) throws Exception {
        Client client = createClient(
                "8Hj0UWMFmmlJRrID",
                "wYlYzbMVuc3gDofjhgFlZ4T3uyNaig");
        JSONObject object = new JSONObject();
        object.put("code", code);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("门道生涯")
                .setTemplateCode("SMS_217875284")
                .setTemplateParam(object.toJSONString());
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sms = client.sendSms(sendSmsRequest);
        System.out.println("sms = " + sms.getBody().getCode());
        System.out.println("sms = " + sms.getBody().getMessage());
        return sms.getBody().getCode().equals("OK");
    }

}
